package com.celesea.framework.util;

import com.celesea.configuration.security.bean.AuthorityUser;
import com.celesea.configuration.security.bean.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 环境工具类，用于获取环境参数，例如登录信息，品牌信息等
 */
public class EnvUtil {

    private static final Long BRAND_LOGIN_FLAG = -1L;

    /**
     * 获取 HttpServletRequest
     */
    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();
        return response;
    }

    /**
     * HttpServletRequest
     *
     * @return request
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request;
    }

    private static AuthorityUser getAuthorityUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (AuthorityUser) authentication.getPrincipal();
    }

    public static Long getBrandId() {
        return getAuthorityUser().getSsoLoginInfo().getBrand().getId();
    }

    public static boolean isBrandLogin() {
        Long shopId = getShopId();
        return BRAND_LOGIN_FLAG.equals(shopId);
    }

    public static boolean isAuthority() {
        return SecurityContextHolder.getContext().getAuthentication() != null;
    }

    public static Long getShopId() {
        return getAuthorityUser().getSsoLoginInfo().getCurrentShopId();
    }

    public static String getShopName() {
        return getAuthorityUser().getSsoLoginInfo().getCurrentShopName();
    }

    public static User getLoginUser() {
        return getAuthorityUser().getSsoLoginInfo().getUser();
    }

}
